package cn.kgc.javaweb.servlet;

import cn.hutool.crypto.SecureUtil;
import cn.kgc.javaweb.entity.User;
import cn.kgc.javaweb.service.UserService;
import cn.kgc.javaweb.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: mosin
 * @version: v1.0  2022/6/25
 */
@WebServlet("/user")
public class UserServlet extends BaseServlet {


    private UserService userService =  new UserServiceImpl();

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = User.builder().userName(username).password(SecureUtil.md5(password)).build();
        Boolean b = userService.selectByUser(user);

        if(b){
            //非法请求拦截的判定条件
            req.getSession().setAttribute("user", user);
            //调用接口 查询所有学生信息 跳转学生信息展示页
            resp.sendRedirect(req.getContextPath()+"/student?method=toList");
        }else {

            req.setAttribute("info", "用户名或密码错误");
            req.getRequestDispatcher("login.jsp").forward(req, resp);

        }


    }


    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = User.builder().userName(username).password(SecureUtil.md5(password)).build();
        Boolean b = userService.addUser(user);


        if(b){
            //注册成功 跳转登录页
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
        }else {
            // 注册失败 添加失败信息
            req.setAttribute("info", "注册失败");
            req.getRequestDispatcher("register.jsp").forward(req, resp);

        }

    }


    protected void checkUserName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {




    }
}
